<template>
  <plain-page>
    <el-card
      shadow="never"
      :style="{
        'border-top': '2px solid',
        'border-top-color': orderInfo.status == null ? '#FFF' : StatusTag.colors[orderInfo.status]
      }"
      class="section"
      >
      <div style="height:32px;line-height:32px;">
        <span>{{orderOutName}}</span>
        <span class="order-no">{{orderInfo.orderno}}</span>
        <status-tag v-if="orderInfo.status != null" size="large" :status="orderInfo.status" :type="$params.type" />
        <div v-show="orderInfo.status" class="order-operations">
          <el-button
            v-if="
              $auth('start')
              && ['housekeeping'].includes(orderInfo.industryId)
              && (orderInfo.status >= 13
              && orderInfo.status != 16
              && !loadings.orderFlowInfo
              && !orderFlowInfo.orderStartTime)"
            type="primary"
            plain
            round
            @click="onFlowStartClick"
          >
            开始
          </el-button>
          <el-button
            v-else-if="
              $auth('finish')
              && ['housekeeping', 'catering'].includes(orderInfo.industryId)
              && (orderInfo.status >= 13
              && orderInfo.status != 16
              && !loadings.orderFlowInfo
              && !orderFlowInfo.orderEndTime)"
            type="success"
            round
            plain
            @click="onFlowFinishClick"
          >
            完成
          </el-button>
          <el-button
            v-else-if="
              $auth('comment')
              && ['housekeeping', 'catering'].includes(orderInfo.industryId)
              && (orderInfo.status == 15 && !loadings.orderFlowInfo && !orderFlowInfo.starLevel)"
            type="primary"
            plain
            round
            @click="onCommentClick"
          >
            评价
          </el-button>
          <el-button
            v-if="
              $auth('cancel')
              && ['housekeeping', 'catering'].includes(orderInfo.industryId)
              && [10, 12, 13, 14].includes(orderInfo.status)"
            type="warning"
            plain
            round
            @click="onCancelClick"
          >
            取消
          </el-button>
          <el-dropdown
            v-auth:update
            placement="bottom-start"
            trigger="hover"
            @command="onOrderModifyCommand"
            class="order-update-ops"
          >
            <el-button
              type="danger"
              plain
              circle
              icon="el-icon-edit"
            />
            <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-if="orderFlowInfo.orderStartTime" command="flow-start">修改订单开始记录</el-dropdown-item>
                <el-dropdown-item v-if="orderFlowInfo.orderEndTime" command="flow-finish">修改订单完成记录</el-dropdown-item>
                <el-dropdown-item command="remark">修改订单备注</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <delete-confirm-button
            v-auth:delete
            icon
            :tooltip="{content: '删除订单'}"
            @ok="onDeleteClick(row)"
          />
        </div>
      </div>
    </el-card>
    <el-card shadow="never" body-style="padding: 10px 20px;" class="section" :class="{hide: orderInfo.status == null || orderInfo.status == 0}">
      <table class="info-table">
        <tr>
          <th>支付状态：</th>
          <td colspan="3">
            <pay-status-tag :status="orderInfo.payStatus" />
          </td>
        </tr>
        <tr>
          <th>{{orderOutName}}金额：</th>
          <td colspan="3" class="order-amount">
            {{orderInfo.paymentFee > 0 ? `${orderInfo.paymentFee.toFixed(2)}` : '免费'}}
          </td>
        </tr>
        <tr>
          <th>商家店铺：</th>
          <td colspan="3">
            <el-button type="text" size="medium" @click="onProviderDetailsClick(row)">{{orderInfo.providerName}}</el-button>
          </td>
        </tr>
        <tr>
          <th>工单地址：</th>
          <td colspan="3">
            <span>{{orderInfo.address}}</span>
            <el-button
              v-if="orderInfo.longitude && orderInfo.latitude"
              type="text"
              size="medium"
              icon="el-icon-location"
              @click="onLocationClick"
            >定位</el-button>
          </td>
        </tr>
        <tr>
          <th>预估时长：</th>
          <td colspan="3">{{orderInfo.duration}}分钟</td>
        </tr>
        <tr>
          <th>{{orderOutName}}备注：</th>
          <td colspan="3" v-html="(orderInfo.remark && orderInfo.remark.split('\n').join('<br>')) || '无'"></td>
        </tr>
        <tr v-if="orderInfo.industryId == 'housekeeping' && $auth('/smart_info_center/life/user/user/details')">
          <th>服务对象：</th>
          <td>
            <el-button
              type="text"
              size="medium"
              @click="onCreatorDetailsClick"
            >
              <span>{{orderInfo.creatorName}}</span>
            </el-button>
          </td>
        </tr>
        <tr v-else>
          <th>联系人：</th>
          <td>{{orderInfo.linkman}}，{{orderInfo.linkphone}}</td>
        </tr>
      </table>
    </el-card>
    <el-card shadow="never" body-style="padding: 10px 20px;" class="section" :class="{hide: loadings.orderProducts}">
      <el-table
        :data="orderProducts"
        size="medium"
      >
        <el-table-column prop="imageFile" width="100" label="商品" v-slot="{row}">
          <el-image
            fit="cover"
            :src="row.imageFile"
            :preview-src-list="[row.imageFile]"
            style="margin-right: 16px;height: 50px; width: 80px; border-radius: 4px;">
            <image-placeholder slot="error" />
          </el-image>
        </el-table-column>
        <el-table-column prop="productName" width="300"></el-table-column>
        <el-table-column prop="price" width="200" label="单价" :formatter="(row, col, val) => val.toFixed(2)"></el-table-column>
        <el-table-column prop="quantity" label="商品数量"></el-table-column>
      </el-table>
    </el-card>
    <el-card shadow="never" class="section" :class="{hide: loadings.orderFlowInfo}">
      <el-timeline style="padding-inline-start: 4px;">
        <el-timeline-item
          v-if="orderFlowInfo.orderEndTime"
          :timestamp="orderFlowInfo.orderEndTime.substring(0, 19)"
          placement="top"
          color="#67C23A"
        >
          <el-card shadow="never" body-style="padding:0px 20px">
            <h4>完成服务</h4>
            <p>{{orderFlowInfo.orderEndOperator}}&nbsp;&nbsp;完成服务<template v-if="orderFlowInfo.orderEndAddress">于位置&nbsp;&nbsp;{{orderFlowInfo.orderEndAddress}}</template></p>
            <template v-if="orderFlowInfo.orderEndImage">
              <el-image
                v-for="(url, index) in orderFlowInfo.orderEndImage.split(',')"
                :key="index"
                :src="url"
                fit="cover"
                :preview-src-list="previewSrcs(orderFlowInfo.orderEndImage, index)"
                class="order-flow-image"
              />
            </template>
            <p>备注：{{orderFlowInfo.orderEndRemark}}</p>
            <audio v-if="orderFlowInfo.voiceFile" :src="orderFlowInfo.voiceFile" controls style="vertical-align: middle;"></audio>
          </el-card>
        </el-timeline-item>
        <el-timeline-item
          v-if="orderFlowInfo.orderStartTime"
          :timestamp="orderFlowInfo.orderStartTime.substring(0, 19)"
          placement="top"
          color="#409EFF"
        >
          <el-card shadow="never" body-style="padding:0px 20px">
            <h4>开始服务</h4>
            <p>{{orderFlowInfo.orderStartOperator}}&nbsp;&nbsp;开始服务<template v-if="orderFlowInfo.orderStartAddress">于位置&nbsp;&nbsp;{{orderFlowInfo.orderStartAddress}}</template></p>
            <template v-if="orderFlowInfo.orderStartImage">
              <el-image
                v-for="(url, index) in orderFlowInfo.orderStartImage.split(',')"
                :key="index"
                :src="url"
                fit="cover"
                :preview-src-list="previewSrcs(orderFlowInfo.orderStartImage, index)"
                class="order-flow-image"
              />
            </template>
            <p>备注：{{orderFlowInfo.orderStartRemark}}</p>
          </el-card>
        </el-timeline-item>
        <el-timeline-item
          :timestamp="orderInfo.createTime"
          placement="top"
          color="#E6A23C"
        >
          <el-card shadow="never" body-style="padding:0px 20px">
            <h4>创建订单</h4>
            <p>服务对象：{{orderInfo.creatorName}}</p>
          </el-card>
        </el-timeline-item>
      </el-timeline>
    </el-card>
    <el-card shadow="never" body-style="padding: 10px 20px;" class="section" :class="{hide: loadings.orderFlowInfo}">
      <template slot="header">{{orderOutName}}评价</template>
      <table class="info-table">
        <tr>
          <th>分数评价：</th>
          <td colspan="3">
            <el-rate v-model="orderFlowInfo.starLevel" disabled style="display:inline-block" />
            <template v-if="isNaN(parseInt(orderFlowInfo.starLevel))">（未评价）</template>
          </td>
        </tr>
        <tr>
          <th>文字评价：</th>
          <td colspan="3" style="height: 40px;word-break: break-all;">{{orderFlowInfo.appraiseMessage}}</td>
        </tr>
      </table>
    </el-card>

    <start-form ref="startForm" />
    <finish-form ref="finishForm" />
    <comment ref="comment" />
  </plain-page>
</template>

<script>
import StatusTag from './StatusTag';
import PayStatusTag from './PayStatusTag';
import ImagePlaceholder from '@/components/ImagePlaceholder';

export default {
  pageProps: {
    title({params, subTitle}) {
      return subTitle(params.order.orderno, params.type != 'service' ? '订单详情' : '工单详情');
    }
  },
  components: {
    StatusTag,
    PayStatusTag,
    ImagePlaceholder,
    StartForm: () => import('./flow/StartForm.vue'),
    FinishForm: () => import('./flow/FinishForm.vue'),
    Comment: () => import('./flow/Comment.vue')
  },
  data() {
    return {
      permission: '/pension_service_center/provider/shop/order',
      orderOutName: this.$params.type == 'service' ? '工单' : '订单',
      orderInfo: {
        status: null,
        ...this.$params.order,
      },
      orderFlowInfo: {},
      orderProducts: [],
      loadings: {
        orderFlowInfo: true,
        orderProducts: true
      },
      StatusTag,
    }
  },
  async mounted() {
    const orderCode = this.orderInfo.orderno;
    if ((typeof this.$params.order.status == 'undefined') || !this.$params.order.updateTime) {//没有传递过来完整的订单实体，则查询
      const ret = await this.$http.get('/api/shop/order/details', {params: { orderCode: this.$params.order.orderno }});
      if (!ret.orderno) {
        this.orderInfo.status = 0;
        return;
      }
      Object.assign(this.orderInfo, ret);
    }

    this.$http.get('/api/shop/order/orderDetailPage', {params: {orderno: orderCode}})
      .then(page => {
        this.orderProducts = page.rows;
        this.loadings.orderProducts = false;
      });
    this.$http.get('/api/shop/order/orderFlowInfo', {params: { orderCode }})
      .then(ret => {
        this.orderFlowInfo = ret;
        this.loadings.orderFlowInfo = false;
      });
  },
  methods: {
    onFlowStartClick() {
      const { order } = this.$params;
      this.$refs.startForm.show({
        order,
        onSuccess: () => {
          order.startFlowTime = 1;
          this.refreshOrderFlowInfo();
        }
      });
    },
    onFlowFinishClick() {
      const { order } = this.$params;
      this.$refs.finishForm.show({
        order,
        onSuccess: () => {
          order.endFlowTime = 1;
          this.refreshOrderFlowInfo();
        }
      });
    },
    onCommentClick() {
      const { order } = this.$params;
      this.$refs.comment.show({
        order,
        onSuccess: (form) => {
          order.starLevel = form.starLevel;
          this.refreshOrderFlowInfo();
        }
      });
    },
    onCancelClick() {
      const { order } = this.$params;
      this.$confirm(`确认取消订单 ${order.orderno} ？`, {
        type: 'warning'
      }).then(async () => {
         const ret = await this.$http.post('/api/shop/order/cancel', {
           orderno: order.orderno,
           creator: order.creator,
           operator: ''
         });
         if (ret.success) {
           this.$message.success('取消订单成功');
           order.status = 16;
         }
      });
    },
    onOrderModifyCommand(cmd) {
      const { order } = this.$params;
      switch (cmd) {
        case 'flow-start':
          this.$refs.startForm.show({
            order,
            mode: 'update',
            onSuccess: () => {
              this.refreshOrderFlowInfo();
            }
          });
          break;
        case 'flow-finish':
          this.$refs.finishForm.show({
            order,
            mode: 'update',
            onSuccess: () => {
              this.refreshOrderFlowInfo();
            }
          });
          break;
        case 'remark':
          this.$prompt(null, '修改订单备注', {inputType: 'textarea', inputValue: order.remark, rows: 4}).then(async ({action, value}) => {
            if ('confirm' == action) {
              const ret = await this.$http.post('/api/shop/order/update',
                {orderno: order.orderno, remark: value});
              if (ret.success) {
                this.$message.success('修改成功');
                this.orderInfo.remark = order.remark = value;
              }
            }
          });
          break;
      }
    },
    async onDeleteClick() {
      const ret = await this.$http.post('/api/shop/order/delete', {
        orderno: this.orderInfo.orderno
      });
      if (ret.success) {
        this.$message.success('删除订单成功');
        this.$params.onDeleteSuccess && this.$params.onDeleteSuccess();
      }
    },
    onProviderDetailsClick() {
      let {providerId: id, providerName: name} = this.orderInfo;
      this.pushPage({
        path: '/shop/shop/details',
        params: {
          shop: { id, name }
        },
        key: id
      });
    },
    onCreatorDetailsClick() {
      this.pushPage({
        path: '/user/details',
        params: {
          user: {
            id: this.orderInfo.creator,
            realName: this.orderInfo.creatorName
          }
        }
      });
    },
    onLocationClick() {
      const { orderno } = this.orderInfo;
      if (getModuleContext('shop.orderLocation') && getModuleContext('shop.orderLocation').isCreated()) {
          openModuleByCode('shop.orderLocation');
          getModuleContext('shop.orderLocation').gotoOrder(orderno);
      } else {
        openModuleByCode('shop.orderLocation', {onLoad: function() {
          getModuleContext('shop.orderLocation').gotoOrder(orderno);
        }});
      }
    },
    async refreshOrderFlowInfo() {
      this.orderFlowInfo = await this.$http.get('/api/shop/order/orderFlowInfo',
        {params: { orderCode: this.orderInfo.orderno }});
    },
    previewSrcs(srcCsv, index) {
      const srcs = srcCsv.split(',');
      return srcs.slice(index).concat(srcs.slice(0, index));
    }
  }
}
</script>

<style scoped>
.plain-page {
  margin: 4px auto;
  min-width: 800px;
  max-width: 1200px;
}

.section {
  position: relative;
  margin-top: 4px;
  min-height: max-content;
  transition: .1s border-top,opacity ease-in-out;
}
.section >>> .el-card__header {
  margin-bottom: 8px;
}

.order-operations {
  float: right;
}
.order-operations > .el-button {
  margin-left: 8px;
}
.order-update-ops {
  margin-left: 8px;
}
.confirm-button {
  margin-left: 8px;
}

.order-no {
  margin-right: 16px;
}

.order-amount {
  font-size: 16px !important;
}

.order-flow-image {
  width: 100px;
  height: 100px;
  margin-right: 8px;
  cursor: pointer;
  border-radius: 4px;
}

.info-table {
  width: 100%;
}

.info-table tr {
  height: 33px;
}
.info-table th {
  text-align: right;
  font-size: 14px;
  width: 70px;
  height: 33px;
  font-weight: normal;
}
.info-table td {
  height: 33px;
  text-align: left;
  padding-left: 24px;
  font-size: 14px;
}

.el-timeline .el-timeline-item__content h4 {
  margin: 14px 0px;
}

.hide {
  opacity: 0;
}
</style>